package org.docmanagement.actions;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.docmanagement.commons.struts.CommonAction;
import org.docmanagement.data.Category;
import org.docmanagement.data.Element;
import org.docmanagement.data.File;
import org.docmanagement.forms.IdForm;

/**
 * @author eveno
 * Created on 29 nov. 06
 *
 */
public class SyncWithFileSystemAction extends CommonAction
{
	/**
	 * @see org.docmanagement.commons.struts.BaseDispatchAction#createMethodMap()
	 */
	//@Override
	protected void createMethodMap()
	{
        methodMap = new HashMap<String, String>();
        methodMap.put("SearchFiles", "searchFiles");
	}
    /**
     * 
     */
    public ActionForward searchFiles(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
    	IdForm id = (IdForm) form;
    	Category cat = (Category) getCategoryService().findById(id.getId());
    	java.io.File[] scannedFiles = getRepositoryService().searchFiles(cat);
    	List<? extends Element> elements = getElementService().findByCategoryId(id.getId());
    	List<String> foundFiles = new LinkedList<String>();
    	boolean found = false;
    	for (int i = 0; i < scannedFiles.length; i++)
        {
    		found = false;
    		Iterator<? extends Element> iterator = elements.iterator();
	    	while (iterator.hasNext())
	        {
	    		Element element = (Element) iterator.next();
	    		if (element.getType() == Element.FILE_TYPE)
	    		{
	    			File f = (File) element;
        			if (f.getFile().equals(scannedFiles[i].getName()))
        			{
        				found = true;
        			}
    	        }
    		}
	    	if (!found)
	    		foundFiles.add(scannedFiles[i].getName());
        }
    	request.setAttribute("FILES", foundFiles);
    	return getRessources(mapping, form, request, response);
    }
}
